const snapdom = window.snapdom

AMapLoader.load({
  key: '1202be5c21409cb2830166fb0c32ff0d',
  version: '1.4.15',
  plugins: ['AMap.Scale']
}).then((AMap) => {
  console.log(AMap, '地图依赖加载完成')
})

function generateRangeList(n) {
  const rangeList = []
  for (let i = 0; i < n * n; i++) {
    const rowIndex = Math.floor(i / n)
    const colIndex = i % n
    const centerRow = Math.floor(n / 2)
    const centerCol = Math.floor(n / 2)
    // 旋转角度
    const rowOffset = colIndex - centerCol
    const colOffset = -(rowIndex - centerRow)
    rangeList.push([rowOffset, colOffset])
  }
  return rangeList
}

new Vue({
  el: '#app',
  data() {
    return {
      formData: {
        center: '104.065861,30.657401', // 天府广场
        // center: '103.928427,30.773304', // 万景峰
        mapZoom: 15,
        areaSize: 800,
        areaEdgeCount: 3
      },
      type: 1,
      mapWidth: 0,
      mapHeight: 0,
      exportCanvasWidth: 0,
      createPercentage: 0
    }
  },
  created() {
    const mapSliceCenter = sessionStorage.getItem('map-slice-center')
    if (mapSliceCenter) {
      this.formData.center = mapSliceCenter
    }
  },
  methods: {
    createMap(domId, centerData) {
      const center = Array.isArray(centerData) ? centerData : centerData.split(',').map(Number)
      return new Promise((resolve) => {
        const { mapZoom, areaSize } = this.formData
        const dom = document.getElementById(domId)
        dom.innerHTML = ''
        dom.style.width = `${areaSize}px`
        dom.style.height = `${areaSize}px`
        const map = new AMap.Map(dom, { zoom: mapZoom, center })
        map.on('complete', () => setTimeout(() => resolve(map), 200))
      })
    },
    async preview() {
      this.type = 1
      const { center } = this.formData
      const res = await this.createMap('preview-container', center)
      const { northeast, southwest } = res.getBounds()
      this.mapWidth = northeast.lng - southwest.lng
      this.mapHeight = northeast.lat - southwest.lat
      console.log(this.mapWidth, this.mapHeight, '地图宽高')
      sessionStorage.setItem('map-slice-center', this.formData.center)
    },
    async onSubmit() {
      await this.preview()
      this.type = 2
      await this.$nextTick()
      const createContainer = document.getElementById('create-container')
      createContainer.innerHTML = ''
      const { areaEdgeCount } = this.formData
      const center = this.formData.center.split(',').map(Number)
      // 创建地图切片容器
      const sumCount = areaEdgeCount * areaEdgeCount
      for (let i = 0; i < sumCount; i++) {
        const div = document.createElement('div')
        div.id = `area-${i}`
        createContainer.appendChild(div)
      }
      // 生成地图切片
      const rangeList = generateRangeList(areaEdgeCount)
      let exportCanvasWidth = 0
      const imagesBox = document.querySelector('.images_box')
      imagesBox.style.gridTemplateColumns = `repeat(${areaEdgeCount}, auto)`
      for (let index = 0; index < rangeList.length; index++) {
        const item = rangeList[index]
        const [sX, sY] = item
        const [x, y] = center
        const id = `area-${index}`
        await this.createMap(id, [x + sX * this.mapWidth, y + sY * this.mapHeight])
        // 截图
        console.log('截图', id, item)
        const image = await snapdom.toPng(document.querySelector(`#${id} .amap-layers`))
        document.getElementById(id).innerHTML = ''
        if (exportCanvasWidth == 0) {
          exportCanvasWidth = image.width
        }
        imagesBox.appendChild(image)
        this.createPercentage = parseFloat(Math.ceil(((index + 1) / sumCount) * 100))
      }
      createContainer.innerHTML = ''
      this.exportCanvasWidth = exportCanvasWidth
    },
    async downHandle() {
      const dom = document.querySelector('.images_box')
      const areaEdgeCount = this.formData.areaEdgeCount
      const w = this.exportCanvasWidth
      dom.style.width = w * areaEdgeCount + 'px'
      dom.style.height = w * areaEdgeCount + 'px'
      const capture = await snapdom(dom)
      await capture.download({
        format: 'png',
        filename: `export-${Date.now()}`
      })
    }
  }
})
